package com.proxy.spring;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * @author van
 * 2021年01月10日23:34:56
 * json转换工具
 */
public class JsonMapper {

    private static final ObjectMapper jsonMapper = new ObjectMapper();

    static {
        jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        jsonMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {//设置默认字符串属性为""
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeString("");
            }
        });
    }

    public static ObjectMapper getJsonMapper() {
        return jsonMapper;
    }

    public static String toJson(Object obj) {
        if (obj == null || obj instanceof String)
            return (String) obj;

        try {
            return jsonMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("failed to write to json " + obj.getClass());
        }
    }


}
